<?php
/**
 * Create by Phpstorm
 * User: Peco
 * Date: 2019/12/12
 * Time: 10:21
 */

namespace App\Http\Controllers\Api;

use App\Http\Requests\Sms\AddSettingSmsRequest;
use App\Http\Requests\Sms\AgainSendSingleSmsRequest;
use App\Http\Requests\Sms\DeleteSettingSmsRequest;
use App\Http\Requests\Sms\GetGroupSmsLogPageRequest;
use App\Http\Requests\Sms\GetGroupSmsPageRequest;
use App\Http\Requests\Sms\GetSettingSmsDetailRequest;
use App\Http\Requests\Sms\GetDefaultSmsRequest;
use App\Http\Requests\Sms\SettingDefaultSmsRequest;
use App\Http\Requests\Sms\SettingSmsPageRequest;
use App\Http\Requests\Sms\UpdateSettingSmsRequest;
use App\Http\Requests\Sms\GetSmsLogPageRequest;
use App\Http\Requests\UserInfo\SendUserSmsRequest;
use App\Http\Transformers\Sms\GetGroupSmsLogPageTransformer;
use App\Http\Transformers\Sms\GetGroupSmsPageTransformer;
use App\Http\Transformers\Sms\GetSettingSmsDetailTransformer;
use App\Http\Transformers\Sms\GetDefaultSmsTransformer;
use App\Http\Transformers\Sms\SettingSmsPageTransformer;
use App\Http\Transformers\Sms\GetSmsLogPageTransformer;
use App\Jobs\SendGroupNotification;
use App\Jobs\SendUserSms;
use App\Repositories\SmsRepository;
use App\Traits\Setting;
use Illuminate\Support\Facades\Redis;

class SmsController extends BaseAdminController
{
    use Setting;

    /**
     * @var SmsRepository 注入的数据模型
     */
    protected $smsRepository;

    /**
     * SmsController constructor.
     * @param SmsRepository $smsRepository
     */
    public function __construct(SmsRepository $smsRepository)
    {
        $this->smsRepository = $smsRepository;
    }

    /**
     * 添加短信配置
     * @param AddSettingSmsRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function addSettingSms(AddSettingSmsRequest $request){
        $all = $request->all(['key', 'configList', 'isDefault', 'name']);

        if($this->smsRepository->SettingSmsExists($all['key'])){
            $this->response->errorBadRequest('该短信配置已存在！');
        }

        if($sms = $this->smsRepository->addSettingSmsRepository($all)){

            //如果是默认的则缓存
            $value = \GuzzleHttp\json_encode(['key'=>$all['key'], 'value'=>\GuzzleHttp\json_decode($sms->value)]);
            $all['isDefault'] && $this->storeSettingData(DEFAULT_SMS_KEY, $value);

            return $this->response->accepted('', 'success');
        }

        $this->response->errorInternal('保存短信配置失败！');
    }

    /**
     * 编辑短信配置
     * @param UpdateSettingSmsRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function updateSettingSms(UpdateSettingSmsRequest $request){
        $all = $request->all(['id', 'key', 'configList', 'isDefault', 'name']);

        if($all['id'] == $this->smsRepository->getSettingSmsId($all['key'])){
            $this->response->errorBadRequest('该短信配置名称已存在！');
        }

        if($sms = $this->smsRepository->updateSettingSmsRepository($all)){

            //如果是默认的则缓存
            $value = \GuzzleHttp\json_encode(['key'=>$all['key'], 'value'=>\GuzzleHttp\json_decode($sms->value)]);
            $all['isDefault'] && $this->storeSettingData(DEFAULT_SMS_KEY, $value);

            return $this->response->accepted('', 'success');
        }

        $this->response->errorInternal('保存短信配置失败！');
    }

    /**
     * 短信配置分页列表
     * @param SettingSmsPageRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function settingSmsPage(SettingSmsPageRequest $request){
        $limit = $request->get('limit');
        $data = $request->except(['limit', 'page']);

        $page = $this->smsRepository->settingSmsPageRepository($data, $limit);

        return $this->response->paginator($page, new SettingSmsPageTransformer());
    }

    /**
     * 获取短信配置详细信息
     * @param GetSettingSmsDetailRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function getSettingSmsDetail(GetSettingSmsDetailRequest $request){
        $key = $request->get('key');

        $setting = $this->smsRepository->getSettingSmsDetailRepository($key);

        return $this->response->item($setting, new GetSettingSmsDetailTransformer());
    }

    /**
     * 删除短信配置
     * @param DeleteSettingSmsRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function deleteSettingSms(DeleteSettingSmsRequest $request){
        $this->response->errorBadRequest('禁止删除！');exit;

//        $key = $request->get('key');
//
//        if(!$this->smsRepository->getSettingSmsDefaultRepository($key)){
//            $this->response->errorBadRequest('该配置是默认短信配置，不能删除！');
//        }
//
//        $this->smsRepository->deleteSettingSmsRepository($key);
//
//        return $this->response->accepted('', 'success');
    }

    /**
     * 保存默认的短信配置
     * @param SettingDefaultSmsRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function settingDefaultSms(SettingDefaultSmsRequest $request){
        $all = $request->all(['key', 'isDefault']);

        if(!$all['isDefault']){
            $this->response->errorBadRequest('该短信配置是默认的短信配置，不能关闭！');
        }

        if($sms = $this->smsRepository->setDefaultAndUpdateRepository($all['key'], $all['isDefault'])){

            //默认缓存配置
            $value = \GuzzleHttp\json_encode(['key'=>$all['key'], 'value'=>\GuzzleHttp\json_decode($sms->value)]);
            $this->storeSettingData(DEFAULT_SMS_KEY, $value);

            return $this->response->accepted('', 'success');
        }

        $this->response->errorInternal('保存默认短信配置失败！');
    }

    /**
     * 获取短信列表
     * @param GetSmsLogPageRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function getSmsLogPage(GetSmsLogPageRequest $request){
        $limit = $request->get('limit');
        $data = $request->all(['phone', 'userId']);
        $banner = $this->smsRepository->getSmsLogPageRepository($data, $limit);

        return $this->response->paginator($banner, new GetSmsLogPageTransformer());
    }

    /**
     * @param GetDefaultSmsRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function getDefaultSms(GetDefaultSmsRequest $request){
        if($data = $this->getSettingCache(DEFAULT_SMS_KEY)){
            $data = \GuzzleHttp\json_decode($data,true);
            $list = $this->smsRepository->getSettingSmsListRepository($data['key']);
            return $this->response->item($list, new GetDefaultSmsTransformer());
        }

        $this->response->errorBadRequest('无法发送短信，请设置默认短信配置！');

    }

    /**
     * 群发或私发短信
     * @param SendUserSmsRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function sendUserSms(SendUserSmsRequest $request){
        $all = $request->all(['phones', 'content', 'remark']);

        $phones = $all['phones'] ?  explode(',', $all['phones']) : [];

        $gateways = Redis::get(DEFAULT_SMS_KEY);//获取Redis中保存的默认商家短信配置
        $gateways = \GuzzleHttp\json_decode($gateways, true);

        if($groupSmsId = $this->smsRepository->sendUserSmsRepository($all, $gateways)){

            //发分短信
            dispatch((new SendGroupNotification($groupSmsId, $phones, $gateways, $all['content']))
                ->onQueue('high'));

            return $this->response->accepted('', '正在发送中');
        }
        $this->response->errorBadRequest('发送失败');
    }

    /**
     * 获取群发短信列表
     * @param GetSmsLogPageRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function getGroupSmsPage(GetGroupSmsPageRequest $request){
        $limit = $request->get('limit');
        $data = $request->all(['phone', 'userId']);
        $banner = $this->smsRepository->getGroupSmsPageRepository($data, $limit);

        return $this->response->paginator($banner, new GetGroupSmsPageTransformer());
    }

    /**
     * 获取群发短信列表详情
     * @param GetGroupSmsLogPageRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function getGroupSmsLogPage(GetGroupSmsLogPageRequest $request){
        $limit = $request->get('limit');
        $data = $request->all(['phone', 'userId', 'group_sms_id']);
        $banner = $this->smsRepository->getGroupSmsLogPageRepository($data, $limit);

        return $this->response->paginator($banner, new GetGroupSmsLogPageTransformer());
    }

    /**
     * 再次发送短信
     * @param AgainSendSingleSmsRequest $request
     * @return \Dingo\Api\Http\Response
     */
    public function againSendSingleSms(AgainSendSingleSmsRequest $request){
        $id = $request->get('id', 0);

        if($group = $this->smsRepository->getGroupSms($id)){

            //禁止二次发送
            if($group->status == 1 ){
                $this->response->errorBadRequest('该短信已发送成功！');
            }

            //获取Redis中保存的默认商家短信配置
            $gateways = Redis::get(DEFAULT_SMS_KEY);
            $gateways = \GuzzleHttp\json_decode($gateways, true);

            //发分短信
            dispatch((new SendUserSms($group->phone, $group->smsGroupLog->content, $id, $gateways))
                ->onQueue('high'));

            return $this->response->accepted('', '正在发送中');
        }
    }

}
